/***Net By GYLite 2022-12-26
 * 网络信息类，提供网络装，网络操作失败重做接口等
*/
class Net {
	private static _instance: Net;
	public static getInstance(): Net {
		if (!Net._instance) {
			Net._instance = new Net();
		}
		return Net._instance;
	}
	public static DIS_CONNECTED: number = 1;
	public static CONNECTED: number = 0;
	private _waitNetData: any[] = [];
	private _state: number = 0;		
	public constructor() {		
		
	}

	/**检测是否通网，先传入操作方法，待接收到通网后再调用netSendAgain(id)重新执行操作
	 * @param func 操作函数
	 * @param thisObj this
	 * @param param 参数数组 默认null 无参数
	 * @param id 操作id
	 * @return boolean 是否通网
	*/
	public check(func: Function, thisObj: any, param: any[] = null, id: number = 0): boolean {
		let s = this;
		Log.writeLog("NET_保留网络操作-" + id, Log.INFO);
		s._waitNetData.push({ func: func, thisObj: thisObj, param: param, id: id });
		if (s.state == Net.DIS_CONNECTED)
			return false;
		return true;
	}
	/**网络失败重载，进行重试
	 * @param id 网络操作id
	 * @param time 重试时间
	*/
	public netSendAgain(id: number, time: number = 2000): void {
		let s = this;
		if (id == 1)
			Log.writeLog(MultiLang.str58 + "-" + id, Log.WARN);
		else
			Log.writeLog(MultiLang.str68 + "-" + id, Log.WARN);
		GYLite.TimeManager.timeOut(s.doNetSend, s, time, id);
	}
	public doNetSend(id: number): void {
		let s = this;
		let obj: any;
		let i: number, len: number;
		Log.writeLog("NET_重新执行网络操作-" + id + "-" + s._waitNetData.length, Log.IMPORTANT);
		len = s._waitNetData.length;
		for (i = 0; i < len; ++i) {
			obj = s._waitNetData[i];
			if (obj.id == id) {
				obj.func.apply(obj.thisObj, obj.param);
				break;
			}
		}
	}

	public set state(val: number) {
		let s = this;
		s._state = val;		
		if (s._state == Net.DIS_CONNECTED) {
			Log.writeLog("NET_网络断开！", Log.IMPORTANT);
			if (GameManager.inited) {					
			   Dispatcher.getInstance().dispatchEventWith(Dispatcher.Net_DIS);
			}
		}
		else {
			Log.writeLog("NET_网络恢复！需执行操作数：" + s._waitNetData.length, Log.IMPORTANT);
			if (GameManager.inited) {				
				Dispatcher.getInstance().dispatchEventWith(Dispatcher.Net_NET);
			}
		}
	}



	/**网络状态 参考Net常量*/
	public get state(): number {
		return this._state;
	}
	/**某id的联网操作完成*/
	public netComplete(id: number): void {
		let s = this;
		let len: number;
		len = s._waitNetData.length;
		while (--len > -1) {
			if (s._waitNetData[len].id == id) {
				Log.writeLog("NET_网络操作完成-" + id, Log.INFO);
				s._waitNetData.splice(len, 1);
				break;
			}
		}
	}	
}
